package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasPrintTemplateEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.enums.ScreenTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkDetailPojo;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.paas.field.SerialNumberPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.help.menu.InitCrmMenuHelp;
import com.xbongbong.paas.help.menu.InitFundManagementMenuHelp;
import com.xbongbong.paas.help.menu.InitJxcMenuHelp;
import com.xbongbong.paas.help.menu.InitMenuHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.pojo.dto.FormExplainAddDTO;
import com.xbongbong.paas.pojo.dto.InitFundPrintDTO;
import com.xbongbong.paas.pojo.dto.InitQuotationDTO;
import com.xbongbong.paas.pojo.dto.PurchaseInvoiceInitDTO;
import com.xbongbong.paas.print.model.PaasPrintTemplateModel;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.CRMMenuEnum;
import com.xbongbong.pro.enums.menu.enums.JXCMenuEnum;
import com.xbongbong.pro.enums.menu.enums.JXCRemouldMenuEnum;
import com.xbongbong.pro.form.pojo.dto.FormAddBatchDTO;
import com.xbongbong.pro.form.pojo.vo.FormAddBatchVO;
import com.xbongbong.pro.formexplain.pojo.dto.FormExplainAddBatchDTO;
import com.xbongbong.pro.formexplain.pojo.vo.FormExplainAddBatchVO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.script.pojo.dto.PrintTemplateDTO;
import com.xbongbong.pro.script.pojo.dto.ProductDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.ForbiddenSettingEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.PrintTemplateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductionInstockEnum;
import com.xbongbong.saas.enums.business.ProductionMaterielOutstockEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.RefundInstockEnum;
import com.xbongbong.saas.enums.business.ReturnedMaterielInstockEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseOutstockEnum;
import com.xbongbong.saas.enums.business.WorkOrderOutstockEnum;
import com.xbongbong.saas.script.help.InitExplainsHelper;
import com.xbongbong.saas.script.tempenum.SerialNumberEnum;
import com.xbongbong.saas.service.RepairExplainService;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/9/26 15:40
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/module")
public class ModuleInitScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(ModuleInitScriptController.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private InitCrmMenuHelp initCrmMenuHelp;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private PaasPrintTemplateModel paasPrintTemplateModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private InitJxcMenuHelp initJxcMenuHelp;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private RepairExplainService repairExplainService;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private InitFundManagementMenuHelp initFundManagementMenuHelp;

    @RequestMapping(value = "/init", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixPaymentDatabase(@RequestBody @Valid InitQuotationDTO initQuotationDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(initQuotationDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        String userId = initQuotationDTO.getUserId();
        Map<String, Object> param = new HashMap<>(16);
        param.put("del", 0);
        param.put("status", 1);
        int total = companyModel.getEntitysCount(param);
        int pageSize = 1000;

        for (int i = 0; i < total; i += pageSize) {
            param.clear();
            param.put("del", 0);
            param.put("status", 1);
            param.put("start", i);
            param.put("pageNum", pageSize);
            param.put("columns", "corpid");
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            if (Objects.isNull(companyEntityList) || companyEntityList.isEmpty()) {
                continue;
            }
            List<String> corpids = new ArrayList<>(pageSize);
            companyEntityList.forEach(item -> {
                corpids.add(item.getCorpid());
            });
            Map<String, Object> appParam = new HashMap<>();
            appParam.put("del", 0);
            appParam.put("corpidIn", corpids);
            appParam.put("alias", XbbRefTypeEnum.CRM.getAlias());
            List<PaasAppEntity> entitys = paasAppModel.findEntitys(appParam);
            if (Objects.isNull(entitys) || entitys.isEmpty()) {
                continue;
            }
            Integer saasMark = SaasMarkEnum.SAAS.getCode();
            List<PaasMenuEntity> menuAddList = new ArrayList<>();
            Long now = DateTimeUtil.getInt();

            List<Long> appIds = new ArrayList<>(entitys.size());
            entitys.forEach(item -> appIds.add(item.getId()));
            Map<String, Object> menuParam = new HashMap<>();
            menuParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            menuParam.put("appIdList", appIds);
            menuParam.put("parentId", 0);
            menuParam.put("columns", "app_id");
            List<PaasMenuEntity> menuEntities = paasMenuModel.findEntitys(menuParam);
            Map<Long, Integer> appIdAndCount = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasMenuEntity menuEntity : menuEntities) {
                Long appId = menuEntity.getAppId();
                Integer count = appIdAndCount.get(appId);
                if (count == null) {
                    appIdAndCount.put(appId, 0);
                } else {
                    count += 1;
                    appIdAndCount.put(appId, count);
                }
            }

            for (PaasAppEntity item : entitys) {
                PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setCorpid(item.getCorpid());
                paasMenuEntity.setAppId(item.getId());
                paasMenuEntity.setCreatorId(userId);
                paasMenuEntity.setAlias(CRMMenuEnum.QUOTATION.getAlias());
                paasMenuEntity.setColor(CRMMenuEnum.QUOTATION.getAccessLinkEnum().getColor());
                paasMenuEntity.setIcon(CRMMenuEnum.QUOTATION.getAccessLinkEnum().getIcon());
                paasMenuEntity.setParentId(0L);
                paasMenuEntity.setSaasMark(saasMark);
                paasMenuEntity.setUrl(CRMMenuEnum.QUOTATION.getAccessLinkEnum().getUrl());
                paasMenuEntity.setMobileUrl(CRMMenuEnum.QUOTATION.getAccessLinkEnum().getMobileUrl());
                paasMenuEntity.setType(MenuTypeEnum.FORM.getType());
                paasMenuEntity.setEnable(BasicConstant.ZERO);
                paasMenuEntity.setName(CRMMenuEnum.QUOTATION.getName());
                paasMenuEntity.setCreatorId(userId);
                paasMenuEntity.setAddTime(now);
                paasMenuEntity.setUpdateTime(now);

                Integer count = appIdAndCount.get(item.getId());
                if (count != null) {
                    count += 1;
                    paasMenuEntity.setSort(count);
                } else {
                    paasMenuEntity.setSort(100);
                }

                menuAddList.add(paasMenuEntity);
            }
            List<PaasMenuEntity> menuList;
            try {
                menuList = paasMenuModel.insertBatch(menuAddList);
            } catch (Exception e) {
                LOG.error("menu数据库批量插入菜单出错", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 插入菜单对应的表单
            FormAddBatchDTO formAddBatchDTO = new FormAddBatchDTO();
            BeanUtil.copyProperties(initQuotationDTO, formAddBatchDTO);
            List<FormEntityAddDTO> formList = new ArrayList<>();
            // 通过分组菜单，得到需要插入的表单列表
            for (PaasMenuEntity entity : menuList) {
                entity.setEnable(BasicConstant.ONE);
            }
            initCrmMenuHelp.getFormList(formList, menuList);
            formAddBatchDTO.setFormList(formList);
            FormAddBatchVO formAddBatchVO = paasFormService.addBatch(formAddBatchDTO);
            if (Objects.isNull(formAddBatchVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            MenuInitDTO menuInitDTO = new MenuInitDTO();
            BeanUtil.copyProperties(initQuotationDTO, menuInitDTO);
            // 插入表单对应的字段解释
            initCrmMenuHelp.formExplainAddBatch(menuInitDTO, formAddBatchVO);

            // 插入CRM默认打印模板
            initDefaultPrintTemplates(formAddBatchVO.getFormList());
            LOG.warn("count/total----------------------" + (i + companyEntityList.size()) + "/" + total);
        }
        return "success";
    }

    @RequestMapping(value = "/purchaseInvoice", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixPaymentDatabase(@RequestBody @Valid PurchaseInvoiceInitDTO purchaseInvoiceInitDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(purchaseInvoiceInitDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        String userId = purchaseInvoiceInitDTO.getUserId();
        List<String> corpids = new ArrayList<>();
        int total = companyCount();
        int pageSize = 100;
        if (CollectionsUtil.isNotEmpty(purchaseInvoiceInitDTO.getCorpidList())) {
            corpids = purchaseInvoiceInitDTO.getCorpidList();
            total = corpids.size();
        }
        LOG.warn("-----------fixPaymentDatabase start 开始执行进项发票给旧公司刷form脚本-----------");
        long timeStart = DateTimeUtil.getInt();
        for(int i=0; i<total;i += pageSize){
            if(CollectionsUtil.isEmpty(purchaseInvoiceInitDTO.getCorpidList())){
                corpids = corpids(i);
            }
            if(Objects.isNull(corpids) || corpids.isEmpty()){
                continue;
            }
            //先判断是否有菜单
            List<PaasAppEntity> entities = appEnableList(corpids,XbbRefTypeEnum.FUND_MANAGEMENT.getAlias());
            if(Objects.isNull(entities) || entities.isEmpty()){
                continue;
            }
            //应用ids
            List<Long> appIds = new ArrayList<>(entities.size());
            entities.forEach(item -> appIds.add(item.getId()));
            Map<String, Object> menuParam = new HashMap<>();
            //进销存如果没有开启分两种情况 1 从未开启，第一次开启时初始化 这种情况不需要处理 2 开启了 又关闭了这种情况
            menuParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            menuParam.put("appIdList", appIds);
            menuParam.put("corpidIn",corpids);
            menuParam.put("parentId", 0);
            menuParam.put("alias",XbbRefTypeEnum.PURCHASE_INVOICE.getAlias());
            List<PaasMenuEntity> menuEntities = paasMenuModel.findEntitys(menuParam);
            Map<String, Object> formParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formParam.put("del", DelEnum.NORMAL.getDel());
            formParam.put("corpidIn", corpids);
            formParam.put("businessType", XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
            List<PaasFormEntityExt> forms = paasFormModel.findEntitys(formParam);
            //如果有了菜单 和 form  则不需要更新
            List<String> hasPurchaseInvoiceMenuList = new ArrayList<>();
            Map<String,PaasMenuEntity> paasMenuEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<PaasMenuEntity> shouldInitList = new ArrayList<>();
            //是否存在进项发票菜单
            menuEntities.forEach(paasMenuEntity -> {
                hasPurchaseInvoiceMenuList.add(paasMenuEntity.getCorpid());
                paasMenuEntityMap.put(paasMenuEntity.getCorpid(),paasMenuEntity);
            });
            if(CollectionsUtil.isNotEmpty(forms)) {
                for (PaasFormEntityExt paasFormEntityExt : forms) {
                    if (hasPurchaseInvoiceMenuList.contains(paasFormEntityExt.getCorpid())) {
                        continue;
                    }
                    if (Objects.nonNull(paasMenuEntityMap.get(paasFormEntityExt.getCorpid()))) {
                        shouldInitList.add(paasMenuEntityMap.get(paasFormEntityExt.getCorpid()));
                    }
                }
            }else {
                shouldInitList.addAll(menuEntities);
            }
            FormAddBatchDTO formAddBatchDTO = new FormAddBatchDTO();
            BeanUtil.copyProperties(purchaseInvoiceInitDTO,formAddBatchDTO);
            List<FormEntityAddDTO> formList = new ArrayList<>();
            initFundManagementMenuHelp.getFormList(formList,shouldInitList);
            formAddBatchDTO.setFormList(formList);
            FormAddBatchVO formAddBatchVO = paasFormService.addBatch(formAddBatchDTO);
            if(Objects.isNull(formAddBatchVO)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            MenuInitDTO menuInitDTO = new MenuInitDTO();
            BeanUtil.copyProperties(purchaseInvoiceInitDTO,menuInitDTO);
            //插入表单对应的字段解释
            initFundManagementMenuHelp.formExplainAddBatch(menuInitDTO,formAddBatchVO);
            LOG.warn("count/total----------------------" + (i + corpids.size()) + "/" + total);
        }
        LOG.warn("-----------time consume fixPaymentDatabase:" + (DateTimeUtil.getInt() - timeStart));
        LOG.warn("-----------/pro/v1/script/module/purchaseInvoice over");
        return "success";
    }


    @RequestMapping(value = "/fund", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initFundPrint(@RequestBody @Valid InitFundPrintDTO initFundPrintDTO) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(initFundPrintDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        LOG.warn("-----------initFundPrint start 开始执行打印模板处理脚本-----------");
        List<String> corpids = new ArrayList<>();
        long timeStart = DateTimeUtil.getInt();
        int total = companyCount();
        if (CollectionsUtil.isNotEmpty(initFundPrintDTO.getCorpidList())) {
            corpids = initFundPrintDTO.getCorpidList();
            total = corpids.size();
        }
        //获取默认模板：业务类型-默认模板-map
        List<Integer> businessList = initFundPrintDTO.getBusinessList();
        if (CollectionsUtil.isEmpty(businessList)) {
            LOG.error("业务类型不能为空");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        List<Integer> businessTypeIn = initFundPrintDTO.getBusinessList();
        Map<Integer, PaasPrintTemplateEntity> defaultTemplateMap = defaultTemplateMap(businessTypeIn);
        int pageSize = 100;
        for(int i = 0; i < total; i += pageSize) {
            if(CollectionsUtil.isEmpty(initFundPrintDTO.getCorpidList())) {
                corpids = corpids(i);
            }
            if (Objects.isNull(corpids) || corpids.isEmpty()) {
                continue;
            }
            try {
                insertDefaultTemplate(businessTypeIn, corpids, defaultTemplateMap);
            }catch (Exception e){
                LOG.error("初始化打印模板失败：", e);
            }
            LOG.warn("count/total----------------------" + (i + corpids.size()) + "/" + total);
        }
        LOG.warn("-----------time consume initFundPrint:" + (DateTimeUtil.getInt() - timeStart));
        LOG.warn("-----------/pro/v1/script/module/fund over");
        return "success";
    }

    private void initDefaultPrintTemplates(List<PaasFormEntity> formList) throws Exception {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("businessType", XbbRefTypeEnum.QUOTATION.getCode());
        param.put("corpid", "0");
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateModel.list(param);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return;
        }
        Map<Integer, PaasPrintTemplateEntity> defaultTemplateMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasPrintTemplateEntity templateEntity : defaultList) {
            defaultTemplateMap.put(templateEntity.getBusinessType(), templateEntity);
        }
        long now = DateTimeUtil.getInt();
        List<PaasPrintTemplateEntity> insertList = new ArrayList<>();
        for (PaasFormEntity paasFormEntity : formList) {
            Integer businessType = paasFormEntity.getBusinessType();
            PaasPrintTemplateEntity defaultEntity = defaultTemplateMap.get(businessType);
            if (defaultEntity == null) {
                continue;
            }
            PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity();
            paasPrintTemplateEntity.setName("默认模板");
            paasPrintTemplateEntity.setCorpid(paasFormEntity.getCorpid());
            paasPrintTemplateEntity.setAppId(paasFormEntity.getAppId());
            paasPrintTemplateEntity.setMenuId(paasFormEntity.getMenuId());
            paasPrintTemplateEntity.setFormId(paasFormEntity.getId());
            paasPrintTemplateEntity.setCreatorId("0");
            paasPrintTemplateEntity.setAddTime(now);
            paasPrintTemplateEntity.setUpdateTime(now);
            paasPrintTemplateEntity.setBusinessType(businessType);
            paasPrintTemplateEntity.setHtml(defaultEntity.getHtml());
            paasPrintTemplateEntity.setConfigInfo(defaultEntity.getConfigInfo());
            insertList.add(paasPrintTemplateEntity);
        }
        try {
            paasPrintTemplateModel.insertBatch(insertList);
        } catch (Exception e) {
            LOG.error("初始化打印模板失败：", e);
        }
        LOG.warn(insertList.size() + "条打印模板插入成功");
    }


    @RequestMapping(value = "/addStockMenu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public String addStockMenu(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        long start = DateTimeUtil.getInt();
        String userId = productDTO.getUserId();
        Map<String, Object> param = new HashMap<>(16);
        List<String> corpidList = new ArrayList<>();
        param.put("del", 0);
//        param.put("status", 1);
        if (CollectionsUtil.isNotEmpty(productDTO.getCorpidList())) {
            corpidList = productDTO.getCorpidList();
            param.put("corpidIn", corpidList);
        } else {
            corpidList = companyModel.getCorpidList();
        }
        int total = corpidList.size();
        int pageSize = 1000;
        int totalPage = ((total-1) / pageSize) + 1;
        for (int i = 0; i < total; i += pageSize) {
            LOG.warn("addStockMenu:" + i + "/" + totalPage);
            param.clear();
            param.put("del", 0);
//            param.put("status", 1);
            param.put("start", i);
            param.put("pageNum", pageSize);
            param.put("columns", "corpid");
            param.put("corpidIn", corpidList);
            List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
            if (Objects.isNull(companyEntityList) || companyEntityList.isEmpty()) {
                continue;
            }
            List<String> corpids = new ArrayList<>(pageSize);
            companyEntityList.forEach(item -> {
                corpids.add(item.getCorpid());
            });
            Map<String, Object> appParam = new HashMap<>();
            appParam.put("del", 0);
            appParam.put("corpidIn", corpids);
            appParam.put("alias", XbbRefTypeEnum.JXC.getAlias());
            List<PaasAppEntity> entitys = paasAppModel.findEntitys(appParam);
            if (Objects.isNull(entitys) || entitys.isEmpty()) {
                continue;
            }
            Integer saasMark = SaasMarkEnum.SAAS.getCode();
            Long now = DateTimeUtil.getInt();

            List<Long> appIds = new ArrayList<>(entitys.size());
            entitys.forEach(item -> appIds.add(item.getId()));
            Map<String, Object> menuParam = new HashMap<>();
            menuParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            menuParam.put("appIdList", appIds);
            menuParam.put("parentId", 0);
            menuParam.put("columns", "id, app_id, alias,sort");
            List<PaasMenuEntity> menuEntities = paasMenuModel.findEntitys(menuParam);
            Map<Long, Integer> appIdAndCount = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, Long> stockMap = new HashMap<>(menuEntities.size());
            for (PaasMenuEntity menuEntity : menuEntities) {
                Long appId = menuEntity.getAppId();
                Integer count = appIdAndCount.get(appId);
                if (count == null) {
                    appIdAndCount.put(appId, 0);
                } else {
                    count += 1;
                    appIdAndCount.put(appId, count);
                }
                if (Objects.equals(XbbRefTypeEnum.INVENTORY_MANAGEMENT.getAlias(), menuEntity.getAlias())) {
                    stockMap.put(appId, menuEntity.getId());
                }
            }
            menuParam.remove("parentId");
            menuParam.put("aliasIn", Arrays.asList(XbbRefTypeEnum.OTHER_INSTOCK.getAlias(), XbbRefTypeEnum.OTHER_OUTSTOCK.getAlias(), XbbRefTypeEnum.PURCHASE_INSTOCK.getAlias()));
            List<PaasMenuEntity> otherStockMenuEntities = paasMenuModel.findEntitys(menuParam);
            Map<Long, Integer> instockSortMap = new HashMap<>(menuEntities.size());
            Map<Long, Integer> outstockSortMap = new HashMap<>(menuEntities.size());
            Set<Long> haveNewStockMenuSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasMenuEntity menuEntity : otherStockMenuEntities) {
                Long appId = menuEntity.getAppId();
                if (Objects.equals(XbbRefTypeEnum.OTHER_INSTOCK.getAlias(), menuEntity.getAlias())) {
                    instockSortMap.put(appId, menuEntity.getSort());
                } else if (Objects.equals(XbbRefTypeEnum.OTHER_OUTSTOCK.getAlias(), menuEntity.getAlias())) {
                    outstockSortMap.put(appId, menuEntity.getSort());
                } else if (Objects.equals(XbbRefTypeEnum.PURCHASE_INSTOCK.getAlias(), menuEntity.getAlias())) {
                    haveNewStockMenuSet.add(appId);
                }
            }
            //拿到1000家公司的app
            for (int j = 0; j < entitys.size(); j ++) {
                PaasAppEntity item = entitys.get(j);
                // 生成过采购入库单菜单的就当已经生成过拆分菜单了
                if (haveNewStockMenuSet.contains(item.getId())) {
                    LOG.warn("corpid:" + item.getCorpid() + ",page:" + i + "/" + totalPage + "app page:" + j + "/" + entitys.size() + "has cut");
                    continue;
                }
                PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), item.getCorpid());
                if (Objects.isNull(paasFormEntity)) {
                    LOG.warn("corpid:" + item.getCorpid() + ",page:" + i + "/" + totalPage + "app page:" + j + "/" + entitys.size() + "no product");
                    continue;
                }
                LOG.warn("corpid:" + item.getCorpid() + ",page:" + i + "/" + totalPage + "app page:" + j + "/" + entitys.size());
                Map<String, PaasMenuEntity> groupMenuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<PaasMenuEntity> menuAddList = new ArrayList<>();
                for (JXCRemouldMenuEnum menuEnum : JXCRemouldMenuEnum.values()) {
                    // 初始化分组入库管理和出库管理
                    if (StringUtil.isEmpty(menuEnum.getParent())) {
                        PaasMenuEntity paasMenuEntity = getMenu(item, menuEnum, userId, now, appIdAndCount, groupMenuMap);
                        menuAddList.add(paasMenuEntity);
                    }
                }
                List<PaasMenuEntity> groupMenuList = paasMenuModel.insertBatch(menuAddList);

                if (CollectionsUtil.isNotEmpty(groupMenuList)) {
                    groupMenuList.forEach(groupMenu -> {
                        groupMenuMap.put(groupMenu.getAlias(), groupMenu);
                    });
                }
                List<PaasMenuEntity> formAddMenuList = new ArrayList<>();
                for (JXCRemouldMenuEnum menuEnum : JXCRemouldMenuEnum.values()) {
                    // 初始化二级菜单
                    if (StringUtil.isNotEmpty(menuEnum.getParent())) {
                        PaasMenuEntity paasMenuEntity = getMenu(item, menuEnum, userId, now, instockSortMap, outstockSortMap, groupMenuMap);
                        formAddMenuList.add(paasMenuEntity);
                    }
                }
                List<PaasMenuEntity> formMenuList = paasMenuModel.insertBatch(formAddMenuList);

                // 插入菜单对应的表单
                FormAddBatchDTO formAddBatchDTO = new FormAddBatchDTO();
                BeanUtil.copyProperties(productDTO, formAddBatchDTO);
                formAddBatchDTO.setCorpid(item.getCorpid());
                List<FormEntityAddDTO> formList = new ArrayList<>();
                Map<String, Object> formParam = new HashMap<>();
                formParam.put("del", DelEnum.NORMAL.getDel());
                formParam.put("corpid", item.getCorpid());
                formParam.put("businessTypeList", Arrays.asList(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()));
                List<PaasFormEntityExt> forms = paasFormModel.findEntitys(formParam);
                getFormList(formList, formMenuList, forms);
                formAddBatchDTO.setFormList(formList);
                FormAddBatchVO formAddBatchVO = paasFormService.addBatch(formAddBatchDTO);
                if (Objects.isNull(formAddBatchVO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }

                MenuInitDTO menuInitDTO = new MenuInitDTO();
                BeanUtil.copyProperties(productDTO, menuInitDTO);
                menuInitDTO.setCorpid(item.getCorpid());
                // 插入表单对应的字段解释
                menuInitDTO.setProductForm(paasFormEntity);
                stockFormExplainAddBatch(menuInitDTO, formAddBatchVO);
                // 将线上入库单和出库单、库存查询修改下；
                param.clear();
                param.put("aliasIn", Arrays.asList(XbbRefTypeEnum.OTHER_INSTOCK.getAlias(), XbbRefTypeEnum.OTHER_OUTSTOCK.getAlias(), XbbRefTypeEnum.STOCK_SEARCH.getAlias()));
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("typeIn", Arrays.asList(MenuTypeEnum.FORM.getType(), MenuTypeEnum.MENU.getType(), MenuTypeEnum.PROCESS_FORM.getType()));
                param.put(StringConstant.CORPID, item.getCorpid());
                param.put("appId", item.getId());
                List<PaasMenuEntity> onlineMenuList = paasMenuModel.findEntitys(param);
                if (Objects.isNull(onlineMenuList)) {
                    LOG.error("update menu：", item.getCorpid() + " failure");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "更新线上入库单、出库单、库存查询失败，终止交易");
                }
                List<PaasMenuEntity> updateMenuList = new ArrayList<>();
                onlineMenuList.forEach(updateMenu -> {
                    PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                    paasMenuEntity.setId(updateMenu.getId());
                    paasMenuEntity.setCorpid(updateMenu.getCorpid());
                    if (Objects.equals(XbbRefTypeEnum.OTHER_INSTOCK.getAlias(), updateMenu.getAlias())) {
                        paasMenuEntity.setName(XbbRefTypeEnum.OTHER_INSTOCK.getName());
                        paasMenuEntity.setParentId(groupMenuMap.get(JXCMenuEnum.OTHER_INSTOCK.getParent()).getId());
                        paasMenuEntity.setMobileUrl(AccessLinkEnum.OTHER_INSTOCK.getMobileUrl());
                    } else if (Objects.equals(XbbRefTypeEnum.OTHER_OUTSTOCK.getAlias(), updateMenu.getAlias())) {
                        paasMenuEntity.setName(XbbRefTypeEnum.OTHER_OUTSTOCK.getName());
                        paasMenuEntity.setParentId(groupMenuMap.get(JXCMenuEnum.OTHER_OUTSTOCK.getParent()).getId());
                        paasMenuEntity.setMobileUrl(AccessLinkEnum.OTHER_OUTSTOCK.getMobileUrl());
                    } else if (Objects.equals(XbbRefTypeEnum.STOCK_SEARCH.getAlias(), updateMenu.getAlias())) {
                        paasMenuEntity.setName(updateMenu.getName());
                        paasMenuEntity.setParentId(stockMap.get(updateMenu.getAppId()));
                        paasMenuEntity.setMobileUrl(AccessLinkEnum.STOCK_SEARCH.getMobileUrl());
                    }
                    updateMenuList.add(paasMenuEntity);
                });
                if (!updateMenuList.isEmpty()){
                    paasMenuModel.updateBatch(updateMenuList, item.getCorpid());
                }
                // 插入默认打印模板
//                initDefaultPrintTemplates(formAddBatchVO.getFormList());
            }
        }
      /*  if (true) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }*/
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("addStockMenu over");
        return "success";
    }

    @RequestMapping(value = "/addStockFlowBillMenu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public String addStockFlowBillMenu(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        String userId = productDTO.getUserId();
        Map<String, Object> param = new HashMap<>(16);
        List<String> corpidList = productDTO.getCorpidList();
        param.put("del", 0);
        param.put("status", 1);
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        int totalCount = corpidList.size();
        int pageSize = 500;
        int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
        Long now = DateTimeUtil.getInt();
        for (int page = 0; page < totalPage; page++) {
            int start = page * pageSize;
            int end;
            if (page == totalPage - 1) {
                end = start + lastPageSize;
            } else {
                end = start + pageSize;
            }
            List<String> pageCorpIdList = new ArrayList<>(corpidList.subList(start, end));
            Map<String, Object> menuParam = new HashMap<>();
            menuParam.put("corpidIn", pageCorpIdList);
            menuParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            menuParam.put("alias", XbbRefTypeEnum.INVENTORY_MANAGEMENT.getAlias());
            menuParam.put("columns", "id, app_id, alias");
            List<PaasMenuEntity> menuEntities = paasMenuModel.findEntitys(menuParam);

            Map<Long, Long> stockMap = new HashMap<>(menuEntities.size());
            for (PaasMenuEntity menuEntity : menuEntities) {
                stockMap.put(menuEntity.getAppId(), menuEntity.getId());
            }
            menuParam.put("parentIdList", stockMap.values());
            menuParam.remove("alias");
            List<PaasMenuEntity> childMenuEntities = paasMenuModel.findEntitys(menuParam);
            Map<Long, Integer> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            childMenuEntities.forEach(item -> {
                Integer sort = sortMap.getOrDefault(item.getParentId(), 0);
                sortMap.put(item.getAppId(), ++sort);
            });

            for (PaasMenuEntity item : menuEntities) {
                List<PaasMenuEntity> formAddMenuList = new ArrayList<>();
                List<JXCMenuEnum> menuEnums = Arrays.asList(JXCMenuEnum.STOCK_FLOW_BILL, JXCMenuEnum.STOCK_STANDING_BOOK);
                for (JXCMenuEnum menuEnum : menuEnums) {
                    PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                    paasMenuEntity.setCorpid(item.getCorpid());
                    paasMenuEntity.setAppId(item.getAppId());
                    paasMenuEntity.setCreatorId(userId);
                    paasMenuEntity.setAlias(menuEnum.getAlias());
                    paasMenuEntity.setColor(menuEnum.getAccessLinkEnum().getColor());
                    paasMenuEntity.setIcon(menuEnum.getAccessLinkEnum().getIcon());
                    paasMenuEntity.setParentId(item.getId());
                    paasMenuEntity.setSort(sortMap.getOrDefault(item.getId(), 6));
                    paasMenuEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    paasMenuEntity.setUrl(menuEnum.getAccessLinkEnum().getUrl());
                    paasMenuEntity.setMobileUrl(menuEnum.getAccessLinkEnum().getMobileUrl());
                    paasMenuEntity.setType(menuEnum.getType());
                    paasMenuEntity.setEnable(BasicConstant.ONE);
                    paasMenuEntity.setName(menuEnum.getName());
                    paasMenuEntity.setCreatorId(userId);
                    paasMenuEntity.setAddTime(now);
                    paasMenuEntity.setUpdateTime(now);
                }
                List<PaasMenuEntity> formMenuList = paasMenuModel.insertBatch(formAddMenuList);
            }
        }
        return "success";
    }
    @RequestMapping(value = "/addCostAdjustMenu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public String addCostAdjustMenu(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        LOG.warn("---------------- 成本调整单初始化开始 -------------------");
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        long startTime = DateTimeUtil.getInt();
        List<String> errorCorpidList = new ArrayList<>();
        String userId = productDTO.getUserId();
        Map<String, Object> param = new HashMap<>(16);
        List<String> corpidList = productDTO.getCorpidList();
        param.put("del", 0);
        param.put("status", 1);
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getJxcCorpidListTemporary();
            corpidList.add("0");
        }
        int count = 0;
        //过滤未开启过进销存的公司
        int totalCount = corpidList.size();
        int pageSize = 500;
        int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
        Long now = DateTimeUtil.getInt();
        for (int page = 0; page < totalPage; page++) {
            int start = page * pageSize;
            int end;
            if (page == totalPage - 1) {
                end = start + lastPageSize;
            } else {
                end = start + pageSize;
            }
            List<String> pageCorpIdList = new ArrayList<>(corpidList.subList(start, end));
            Map<String, Object> menuParam = new HashMap<>();
            menuParam.put("corpidIn", pageCorpIdList);
            menuParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            menuParam.put("alias", XbbRefTypeEnum.INVENTORY_MANAGEMENT.getAlias());
            List<PaasMenuEntity> menuEntities = paasMenuModel.findEntitys(menuParam);

            Map<Long, Long> stockMap = new HashMap<>(menuEntities.size());
            for (PaasMenuEntity menuEntity : menuEntities) {
                stockMap.put(menuEntity.getAppId(), menuEntity.getId());
            }
            menuParam.put("parentIdList", stockMap.values());
            menuParam.remove("alias");
            List<PaasMenuEntity> childMenuEntities = paasMenuModel.findEntitys(menuParam);
            Map<Long, Integer> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            childMenuEntities.forEach(item -> {
                Integer sort = sortMap.getOrDefault(item.getParentId(), 0);
                sortMap.put(item.getAppId(), ++sort);
            });

            for (PaasMenuEntity item : menuEntities) {
                String corpid = item.getCorpid();
                try {
                    PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
                    if (Objects.isNull(paasFormEntity)) {
                        paasFormEntity = paasFormModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(),corpid);
                    }
                    List<PaasMenuEntity> formAddMenuList = new ArrayList<>();
                    List<JXCMenuEnum> menuEnums = Arrays.asList(JXCMenuEnum.COST_ADJUST);
                    // 插入菜单
                    for (JXCMenuEnum menuEnum : menuEnums) {
                        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                        paasMenuEntity.setCorpid(item.getCorpid());
                        paasMenuEntity.setAppId(item.getAppId());
                        paasMenuEntity.setCreatorId(userId);
                        paasMenuEntity.setAlias(menuEnum.getAlias());
                        paasMenuEntity.setColor(menuEnum.getAccessLinkEnum().getColor());
                        paasMenuEntity.setIcon(menuEnum.getAccessLinkEnum().getIcon());
                        paasMenuEntity.setParentId(item.getId());
                        paasMenuEntity.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                        paasMenuEntity.setSort(10);
                        paasMenuEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
                        paasMenuEntity.setUrl(menuEnum.getAccessLinkEnum().getUrl());
                        paasMenuEntity.setMobileUrl(menuEnum.getAccessLinkEnum().getMobileUrl());
                        paasMenuEntity.setType(menuEnum.getType());
                        paasMenuEntity.setEnable(BasicConstant.ONE);
                        paasMenuEntity.setName(menuEnum.getName());
                        paasMenuEntity.setAddTime(now);
                        paasMenuEntity.setUpdateTime(now);
                        formAddMenuList.add(paasMenuEntity);
                    }
                    List<PaasMenuEntity> formMenuList = paasMenuModel.insertBatch(formAddMenuList);
                    // 获取需要插入的表单
                    List<FormEntityAddDTO> formList = initJxcMenuHelp.getFormList(new ArrayList<>(), formAddMenuList);
                    // 插入表单
                    FormAddBatchDTO formAddBatchDTO = new FormAddBatchDTO();
                    BeanUtil.copyProperties(item, formAddBatchDTO);
                    formAddBatchDTO.setFormList(formList);
                    formAddBatchDTO.setUserId(productDTO.getUserId());
                    FormAddBatchVO formAddBatchVO = paasFormService.addBatch(formAddBatchDTO);
                    // 插入JXC默认打印模板
                    initDefaultPrintTemplates(corpid, formAddBatchVO.getFormList(), XbbRefTypeEnum.COST_ADJUST.getAlias(), DistributorMarkEnum.OTHER.getCode());
                    // 插入表单对应的字段解释
                    MenuInitDTO menuInitDTO = new MenuInitDTO();
                    BeanUtil.copyProperties(productDTO, menuInitDTO, true);
                    menuInitDTO.setAlias(XbbRefTypeEnum.ORDER_CENTER.getAlias());
                    menuInitDTO.setProductForm(paasFormEntity);
                    initJxcMenuHelp.formExplainAddBatch(menuInitDTO, formAddBatchVO);
                    ++count;
                } catch (Exception e) {
                    LOG.error("{}公司新增失败，原因：{}", corpid, e);
                    errorCorpidList.add(corpid);
                }
            }
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - startTime));
        LOG.warn("操作成功,本次共更新" + corpidList.size() + "家公司，其中:" + count + " 家已更新");
        LOG.error("更新失败公司ID集合" + errorCorpidList.toString());
        return "success";
    }



    /**
     * @param
     * @return void
     * @description JXC默认表单属性迁移
     * @creator JianTao.Xiong
     * @date 2019/12/18 16:04
     */
    private PaasFormEntityExt oldJXCAttrMove(Integer businessType, String parentAlias, List<PaasFormEntityExt> instockOrOutstockForms) {
        PaasFormEntityExt instockOrOutstockForm = null;
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        XbbRefTypeEnum parentEnum = XbbRefTypeEnum.getByAlias(parentAlias);
        if (Objects.equals(parentEnum, XbbRefTypeEnum.INSTOCK) ) {
            for (PaasFormEntityExt instockForm : instockOrOutstockForms) {
                if (Objects.equals(instockForm.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode())) {
                    instockOrOutstockForm = instockForm;
                }
            }
        } else if (Objects.equals(parentEnum, XbbRefTypeEnum.OUTSTOCK)) {
            for (PaasFormEntityExt outstockForm : instockOrOutstockForms) {
                if (Objects.equals(outstockForm.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())) {
                    instockOrOutstockForm = outstockForm;
                }
            }
        }
        if (Objects.nonNull(instockOrOutstockForm)) {
            String customTitle = instockOrOutstockForm.getCustomTitle();
            JSONArray labels = instockOrOutstockForm.getLabelsList();
            JSONArray summarys = instockOrOutstockForm.getSummaryList();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            JSONArray customerTitles = null;
            if (Objects.nonNull(customTitle)) {
                customerTitles = JsonHelperUtil.parseArray(customTitle);
            }
            attrChange(customerTitles, xbbRefTypeEnum);
            attrChange(labels, xbbRefTypeEnum);
            attrChange(summarys, xbbRefTypeEnum);
            paasFormEntityExt.setCustomTitle(customerTitles.toJSONString());
            paasFormEntityExt.setLabelsList(labels.toJSONString());
            paasFormEntityExt.setSummaryList(summarys.toJSONString());
        }
        return paasFormEntityExt;
    }

    private void attrChange(JSONArray jsonArray, XbbRefTypeEnum xbbRefTypeEnum) {
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            String attr = jsonObject.getString("attr");
            switch (xbbRefTypeEnum) {
                case PURCHASE_INSTOCK:
                    for (PurchaseInstockEnum purchaseInstockEnum : PurchaseInstockEnum.values()) {
                        if (Objects.equals(attr, purchaseInstockEnum.getAttr())) {
                            jsonObject.put("attrName", purchaseInstockEnum.getAttrName());
                        }
                    }
                    break;
                case REFUND_INSTOCK:
                    for (RefundInstockEnum refundInstockEnum : RefundInstockEnum.values()) {
                        if (Objects.equals(attr, refundInstockEnum.getAttr())) {
                            jsonObject.put("attrName", refundInstockEnum.getAttrName());
                        }
                    }
                    break;
                case PRODUCTION_INSTOCK:
                    for (ProductionInstockEnum productionInstockEnum : ProductionInstockEnum.values()) {
                        if (Objects.equals(attr, productionInstockEnum.getAttr())) {
                            jsonObject.put("attrName", productionInstockEnum.getAttrName());
                        }
                    }
                    break;
                case RETURNED_MATERIEL_INSTOCK:
                    for (ReturnedMaterielInstockEnum returnedMaterielInstockEnum : ReturnedMaterielInstockEnum.values()) {
                        if (Objects.equals(attr, returnedMaterielInstockEnum.getAttr())) {
                            jsonObject.put("attrName", returnedMaterielInstockEnum.getAttrName());
                        }
                    }
                    break;
                case CONTRACT_OUTSTOCK:
                    for (ContractOutstockEnum contractOutstockEnum : ContractOutstockEnum.values()) {
                        if (Objects.equals(attr, contractOutstockEnum.getAttr())) {
                            jsonObject.put("attrName", contractOutstockEnum.getAttrName());
                        }
                    }
                    break;
                case RETURNED_PURCHASE_OUTSTOCK:
                    for (ReturnedPurchaseOutstockEnum returnedPurchaseOutstockEnum : ReturnedPurchaseOutstockEnum.values()) {
                        if (Objects.equals(attr, returnedPurchaseOutstockEnum.getAttr())) {
                            jsonObject.put("attrName", returnedPurchaseOutstockEnum.getAttrName());
                        }
                    }
                    break;
                case PRODUCTION_MATERIEL_OUTSTOCK:
                    for (ProductionMaterielOutstockEnum productionMaterielOutstockEnum : ProductionMaterielOutstockEnum.values()) {
                        if (Objects.equals(attr, productionMaterielOutstockEnum.getAttr())) {
                            jsonObject.put("attrName", productionMaterielOutstockEnum.getAttrName());
                        }
                    }
                    break;
                case WORK_ORDER_OUTSTOCK:
                    for (WorkOrderOutstockEnum workOrderOutstockEnum : WorkOrderOutstockEnum.values()) {
                        if (Objects.equals(attr, workOrderOutstockEnum.getAttr())) {
                            jsonObject.put("attrName", workOrderOutstockEnum.getAttrName());
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private FormExplainAddBatchVO stockFormExplainAddBatch(MenuInitDTO menuInitDTO, FormAddBatchVO formAddBatchVO) throws XbbException {
        FormExplainAddBatchVO formExplainAddBatchVO;
        try {
            List<PaasFormEntity> formResultList = formAddBatchVO.getFormList();
            FormExplainAddBatchDTO formExplainAddBatchDTO = new FormExplainAddBatchDTO();
            BeanUtil.copyProperties(menuInitDTO, formExplainAddBatchDTO);
            List<FormExplainAddDTO> formExplainList = new ArrayList<>();
            List<PaasFormExplainEntity> listForUpdateProduct = paasFormExplainModel.getListForUpdateProduct(menuInitDTO.getCorpid(), StockConstant.OTHER_STOCK_TYPE_LIST);
            Map<Integer, List<FieldAttrEntity>> stockExplainMap = new HashMap<>(2);
            for (PaasFormExplainEntity explainEntity : listForUpdateProduct) {
                stockExplainMap.put(explainEntity.getBusinessType(), JSON.parseArray(explainEntity.getExplains(), FieldAttrEntity.class));
            }
            for (PaasFormEntity item : formResultList) {
                FormExplainAddDTO formExplainAddDTO = new FormExplainAddDTO();
                BeanUtil.copyProperties(item, formExplainAddDTO);
                formExplainAddDTO.setFormId(item.getId());
                List<FieldAttrEntity> fieldAttrEntityList;
                if (StockConstant.INSTOCK_TYPE_LIST.contains(item.getBusinessType())) {
                    fieldAttrEntityList = stockExplainMap.get(XbbRefTypeEnum.OTHER_INSTOCK.getCode());
                } else {
                    fieldAttrEntityList = stockExplainMap.get(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode());
                }
                List<FieldAttrEntity> newFieldList = (List<FieldAttrEntity>) CloneUtil.deepClone(fieldAttrEntityList);
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(item.getBusinessType());
                switch (xbbRefTypeEnum) {
                    case PURCHASE_INSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(PurchaseInstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(PurchaseInstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.PURCHASE_INSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), PurchaseInstockEnum.SUPPLIER_ID.getAttr()));

                            } else if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(PurchaseInstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(PurchaseInstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setAttrName(PurchaseInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(PurchaseInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PURCHASE.getCode());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setRelyAttr(PurchaseInstockEnum.SUPPLIER_ID.getAttr());
                                saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.SUPPLIER.getCode());
                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                fieldAttrEntity.setRequired(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInstockEnum.REF_ID_LINKED_TEXT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), PurchaseInstockEnum.SUPPLIER_ID_LINKED_TEXT.getAttr()));
                            }
                        }
                        break;
                    case RETURNED_MATERIEL_INSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedMaterielInstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(ReturnedMaterielInstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(ReturnedMaterielInstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.RETURNED_MATERIEL_INSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(ReturnedMaterielInstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(ReturnedMaterielInstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedMaterielInstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setAttrName(ReturnedMaterielInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(ReturnedMaterielInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
                                fieldAttrEntity.setRequired(1);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                            }
                        }
                        break;
                    // 生产入库单
                    case PRODUCTION_INSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), ProductionInstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(ProductionInstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(ProductionInstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.PRODUCTION_INSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionInstockEnum.TYPE.getAttr())) {
                                // 入库类型隐藏
                                fieldAttrEntity.setShowType(ProductionInstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(ProductionInstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionInstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setAttrName(ProductionInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(ProductionInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
                                fieldAttrEntity.setRequired(1);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                            }
                        }
                        break;
                    // 生产领料单
                    case PRODUCTION_MATERIEL_OUTSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), ProductionMaterielOutstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(ProductionMaterielOutstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(ProductionMaterielOutstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.PRODUCTION_MATERIEL_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionMaterielOutstockEnum.TYPE.getAttr())) {
                                // 入库类型隐藏
                                fieldAttrEntity.setShowType(ProductionMaterielOutstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(ProductionMaterielOutstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionMaterielOutstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setAttrName(ProductionMaterielOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(ProductionMaterielOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
                                fieldAttrEntity.setRequired(1);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionMaterielOutstockEnum.TIME.getAttr())) {
                                fieldAttrEntity.setAttrName(ProductionMaterielOutstockEnum.TIME.getAttrName());
                                fieldAttrEntity.setDefaultName(ProductionMaterielOutstockEnum.TIME.getAttrName());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ProductionMaterielOutstockEnum.EXPRESS_NAME.getAttr())){
                                fieldAttrEntity.setIsDictionary(1);
                            }
                        }
                        break;
                    case WORK_ORDER_OUTSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(WorkOrderOutstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(WorkOrderOutstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.WORK_ORDER_OUTSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(WorkOrderOutstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(WorkOrderOutstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setRequired(WorkOrderOutstockEnum.REF_ID.getRequired());
                                fieldAttrEntity.setAttrName(WorkOrderOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(WorkOrderOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.WORK_ORDER.getCode());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setRelyAttr(WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr());
//                                saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
//                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                // 工单出库单的关联工单的关联字段去掉
                                fieldAttrEntity.setShowEditable(0);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                                fieldAttrEntity.setRequired(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.PRODUCT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.EXTENSION_INFO.getAttr()));
                                newFieldList.add(i + 2, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr()));
                                newFieldList.add(i + 3, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.LINK_CONTACT.getAttr()));
                                newFieldList.add(i + 4, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr()));
                                newFieldList.add(i + 5, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.CUSTOMER_ADDRESS.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.REF_ID_LINKED_TEXT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.LINK_CUSTOMER_HIDE.getAttr()));
                                newFieldList.add(i + 2, repairExplainService.addNewField(XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), WorkOrderOutstockEnum.LINK_CONTACT_HIDE.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.EXPRESS_NAME.getAttr())){
                                fieldAttrEntity.setIsDictionary(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr())){
                                SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                                if (Objects.nonNull(subForm)) {
                                    List<? extends FieldAttrEntity> items = subForm.getItems();
                                    for (int j = 0; j < items.size(); j++) {
                                        FieldAttrEntity fieldAttrEntity1 = items.get(j);
                                        fieldAttrEntity1.setShowEditable(0);
                                        fieldAttrEntity1.setRequired(0);
                                        fieldAttrEntity1.setEditable(0);
                                    }
                                }
                                fieldAttrEntity.setShowEditable(0);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderOutstockEnum.CUSTOMER_ADDRESS.getAttr())){
                                fieldAttrEntity.setShowEditable(0);
                            }

                        }
                        break;
                    case CONTRACT_OUTSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(ContractOutstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(ContractOutstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.CONTRACT_OUTSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(ContractOutstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(ContractOutstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setRequired(ContractOutstockEnum.REF_ID.getRequired());
                                fieldAttrEntity.setAttrName(ContractOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(ContractOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.CONTRACT.getCode());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setRelyAttr(ContractOutstockEnum.LINK_CUSTOMER.getAttr());
                                saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                fieldAttrEntity.setRequired(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.TIME.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), ContractOutstockEnum.LINK_CUSTOMER.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.PRODUCT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), ContractOutstockEnum.CUSTOMER_PHONE.getAttr()));
                                newFieldList.add(i + 2, repairExplainService.addNewField(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), ContractOutstockEnum.CUSTOMER_ADDRESS.getAttr()));
                                newFieldList.add(i + 3, repairExplainService.addNewField(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), ContractOutstockEnum.LINK_CUSTOMER_HIDE.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.EXPRESS_NAME.getAttr())){
                                fieldAttrEntity.setIsDictionary(1);
                            }
                        }
                        break;
                    case REFUND_INSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(RefundInstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(RefundInstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.REFUND_INSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.REFUND_INSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.REFUND_INSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.REFUND_INSTOCK.getCode(), RefundInstockEnum.CUSTOMER_ID.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(RefundInstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(RefundInstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setAttrName(RefundInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(RefundInstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.REFUND_INSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.REFUND.getCode());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setRelyAttr(RefundInstockEnum.CUSTOMER_ID.getAttr());
                                saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                fieldAttrEntity.setRequired(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), RefundInstockEnum.REF_ID_LINKED_TEXT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.REFUND_INSTOCK.getCode(), RefundInstockEnum.CUSTOMER_ID_LINKED_TEXT.getAttr()));
                            }
                        }
                        break;
                    case RETURNED_PURCHASE_OUTSTOCK:
                        for (int i = 0; i < newFieldList.size(); i++) {
                            FieldAttrEntity fieldAttrEntity = newFieldList.get(i);
                            if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(ReturnedPurchaseOutstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(ReturnedPurchaseOutstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.RETURNED_PURCHASE_OUTSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.TIME.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(), ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.TYPE.getAttr())) {
                                fieldAttrEntity.setShowType(ReturnedPurchaseOutstockEnum.TYPE.getShowType());
                                fieldAttrEntity.setEditHide(ReturnedPurchaseOutstockEnum.TYPE.getEditHide());
                                fieldAttrEntity.setScreenType(ScreenTypeEnum.SCREEN_OFF.getType());
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setRequired(ReturnedPurchaseOutstockEnum.REF_ID.getRequired());
                                fieldAttrEntity.setAttrName(ReturnedPurchaseOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setDefaultName(ReturnedPurchaseOutstockEnum.REF_ID.getAttrName());
                                fieldAttrEntity.setBusinessType(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.RETURNED_PURCHASE.getCode());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setRelyAttr(ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getAttr());
                                saasParticularAttributePoJo.setRelyBusiness(XbbRefTypeEnum.SUPPLIER.getCode());
                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                fieldAttrEntity.setRequired(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.REF_ID_LINKED_TEXT.getAttr())) {
                                newFieldList.add(i + 1, repairExplainService.addNewField(XbbRefTypeEnum.REFUND_INSTOCK.getCode(), ReturnedPurchaseOutstockEnum.LINK_SUPPLIER_HIDE.getAttr()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseOutstockEnum.EXPRESS_NAME.getAttr())){
                                fieldAttrEntity.setIsDictionary(1);
                            }
                        }
                        break;
                    default:
                        break;
                }

                // 初始化方法获取字段列表
                formExplainAddDTO.setFormList(newFieldList);
                formExplainList.add(formExplainAddDTO);
            }
            // 其他出入库单解释
            for (int i = 0; i < listForUpdateProduct.size(); i++) {
                PaasFormExplainEntity explainEntity = listForUpdateProduct.get(i);
                List<FieldAttrEntity> explains = JSON.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(explainEntity.getBusinessType());
                switch (xbbRefTypeEnum) {
                    case OTHER_OUTSTOCK:
                        for (int j = 0; j < explains.size(); j++) {
                            FieldAttrEntity fieldAttrEntity = explains.get(j);
                            if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(OutstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(OutstockEnum.SHEET_NO.getAttrName());
                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.OUTSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.OUTSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(OutstockEnum.SHEET_NO.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 不能重复
                                fieldAttrEntity.setNoRepeat(1);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.QT_OUTSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                                fieldAttrEntity.setIsForbidden(0);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr())) {
                                // 将出库类型设置为下拉选项
                                fieldAttrEntity.setAttrName(OutstockEnum.TYPE.getAttrName());
                                List<ItemPoJo> itemPoJos = InitExplainsHelper.setCombItemByEnum(OutstockTypeEnum.class, fieldAttrEntity.getFieldType());
                                List<String> otherOutstockCodeList = Arrays.asList(OutstockTypeEnum.INVENTORY_OUTSTOCK.getName(),
                                        OutstockTypeEnum.TRANSFER_OUTSTOCK.getName(), OutstockTypeEnum.OTHER_OUTSTOCK.getName(),
                                        OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getName());
                                for (ItemPoJo itemPoJo : itemPoJos) {
                                    itemPoJo.setNoDel(1);
                                    itemPoJo.setNoEdit(1);
                                    if (!otherOutstockCodeList.contains(itemPoJo.getText())) {
                                        itemPoJo.setShowType(ShowTypeEnum.NONE.getCode());
                                        itemPoJo.setEditHide(1);
                                    } else {
                                        if (Objects.equals(itemPoJo.getText(), OutstockTypeEnum.OTHER_OUTSTOCK.getName())) {
                                            itemPoJo.setChecked(true);
                                        } else {
                                            itemPoJo.setFieldMap(Arrays.asList(OutstockEnum.REF_ID.getAttr()));
                                            itemPoJo.setShowType(ShowTypeEnum.EXCLUDE_NEW.getCode());
                                        }
                                    }
                                }
                                fieldAttrEntity.setAttrName(OutstockEnum.TYPE.getAttrName());
                                fieldAttrEntity.setDefaultName(OutstockEnum.TYPE.getAttrName());
                                fieldAttrEntity.setEditable(0);
                                fieldAttrEntity.setItems(itemPoJos);
                                fieldAttrEntity.setItemBanDefault(1);
                                fieldAttrEntity.setShowEditable(0);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.WAREHOUSE_ID.getAttr())) {
                                fieldAttrEntity.setLinkedText(OutstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr());
                                fieldAttrEntity.setLinkedType(XbbRefTypeEnum.WAREHOUSE.getCode());
                                fieldAttrEntity.setIsForbidden(0);
                                fieldAttrEntity.setEditable(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setEditable(0);
                                fieldAttrEntity.setShowEditable(0);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.EXPRESS_NAME.getAttr())){
                                fieldAttrEntity.setIsDictionary(1);
                            }
                        }
                        break;
                    case OTHER_INSTOCK:
                        for (int j = 0; j < explains.size(); j++) {
                            FieldAttrEntity fieldAttrEntity = explains.get(j);
                            if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.SHEET_NO.getAttr())) {
                                fieldAttrEntity.setAttrName(InstockEnum.SHEET_NO.getAttrName());
                                fieldAttrEntity.setDefaultName(InstockEnum.SHEET_NO.getAttrName());

                                LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                                linkDetailPojo.setBusinessType(XbbRefTypeEnum.INSTOCK.getCode());
                                linkDetailPojo.setSubBuisenssType(XbbRefTypeEnum.INSTOCK.getCode());
                                linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                                linkDetailPojo.setAttr(InstockEnum.SHEET_NO.getAttr());
                                fieldAttrEntity.setLinkDetail(linkDetailPojo);
                                // 不能重复
                                fieldAttrEntity.setNoRepeat(1);
                                // 默认的编号规则
                                SerialNumberPoJo serialNumberPoJo = InitExplainsHelper.setSerialNumber(SerialNumberEnum.QT_INSTOCK_NO);
                                fieldAttrEntity.setSerialNumber(serialNumberPoJo);
                                fieldAttrEntity.setIsForbidden(0);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.TYPE.getAttr())) {
                                // 将入库类型设置为下拉选项
                                List<ItemPoJo> itemPoJos = InitExplainsHelper.setCombItemByEnum(InstockTypeEnum.class, fieldAttrEntity.getFieldType());
                                List<String> otherInstockCodeList = Arrays.asList(InstockTypeEnum.INVENTORY_INSTOCK.getName(),
                                        InstockTypeEnum.TRANSFER_INSTOCK.getName(), InstockTypeEnum.OTHER_INSTOCK.getName(),
                                        InstockTypeEnum.ASSEMBLE_INSTOCK.getName());
                                for (ItemPoJo itemPoJo : itemPoJos) {
                                    itemPoJo.setNoDel(1);
                                    itemPoJo.setNoEdit(1);
                                    if (!otherInstockCodeList.contains(itemPoJo.getText())) {
                                        itemPoJo.setShowType(ShowTypeEnum.NONE.getCode());
                                        itemPoJo.setEditHide(1);
                                    } else {
                                        if (Objects.equals(itemPoJo.getText(), InstockTypeEnum.OTHER_INSTOCK.getName())) {
                                            itemPoJo.setChecked(true);
                                        } else {
                                            itemPoJo.setFieldMap(Arrays.asList(InstockEnum.REF_ID.getAttr()));
                                            itemPoJo.setShowType(ShowTypeEnum.EXCLUDE_NEW.getCode());
                                        }
                                    }
                                }
                                fieldAttrEntity.setAttrName(InstockEnum.TYPE.getAttrName());
                                fieldAttrEntity.setDefaultName(InstockEnum.TYPE.getAttrName());
                                fieldAttrEntity.setEditable(0);
                                fieldAttrEntity.setItems(itemPoJos);
                                fieldAttrEntity.setItemBanDefault(1);
                                fieldAttrEntity.setShowEditable(0);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.WAREHOUSE_ID.getAttr())) {
                                fieldAttrEntity.setLinkedType(RedundantTemplateTypeEnum.WAREHOUSE.getCode());
                                fieldAttrEntity.setLinkedText(InstockEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr());
                                SaasParticularAttributePoJo saasParticularAttributePoJo = new SaasParticularAttributePoJo();
                                saasParticularAttributePoJo.setMultiCheck(false);
                                saasParticularAttributePoJo.setRelyMode("customer");
                                saasParticularAttributePoJo.setRelyType("base");
                                fieldAttrEntity.setSaasParticularAttributePoJo(saasParticularAttributePoJo);
                                fieldAttrEntity.setIsForbidden(0);
                                fieldAttrEntity.setEditable(1);
                            } else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.REF_ID.getAttr())) {
                                fieldAttrEntity.setEditable(0);
                                fieldAttrEntity.setShowEditable(0);
                                fieldAttrEntity.setForbiddenSettingList(Collections.singletonList(ForbiddenSettingEnum.DISABLE_VISIBLE_CORRELATION_FIELD.getAlias()));
                            }
                        }
                        break;
                    default:
                        break;

                }
                explainEntity.setExplains(JSONArray.toJSONString(explains));
                paasFormExplainModel.update(explainEntity);
            }

            formExplainAddBatchDTO.setFormExplainList(formExplainList);
            formExplainAddBatchVO = paasFormExplainService.addBatch(formExplainAddBatchDTO);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("InitJxcMenuHelp.formExplainAddBatch批量添加表单解释信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formExplainAddBatchVO;
    }

    /**
     * 根据菜单获取表单列表
     *
     * @param formList 表单列表
     * @param menuList 菜单列表
     * @return 返回需要插入的表单列表
     * @throws XbbException 业务异常
     * @author 吴峰
     * @date 2019/1/24 18:43
     */
    public List<FormEntityAddDTO> getFormList(List<FormEntityAddDTO> formList, List<PaasMenuEntity> menuList, List<PaasFormEntityExt> forms) throws XbbException {
        try {
            for (PaasMenuEntity item : menuList) {
                FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
                BeanUtil.copyProperties(item, formEntityAddDTO);
                JXCRemouldMenuEnum jxcMenuEnum = JXCRemouldMenuEnum.getByAlias(item.getAlias());
                if (Objects.isNull(jxcMenuEnum)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.BUSINESS_TYPE_NOT_EXIST);
                }
                // 进销存用表单的alias获取业务
                if (MenuTypeEnum.GROUP.getType().equals(jxcMenuEnum.getType()) || MenuTypeEnum.MENU.getType().equals(jxcMenuEnum.getType())) {
                    continue;
                }
                PaasFormEntityExt paasFormEntityExt = oldJXCAttrMove(jxcMenuEnum.getCode(), jxcMenuEnum.getParent(), forms);
                String customTitle = paasFormEntityExt.getCustomTitle();
                JSONArray labelsList = paasFormEntityExt.getLabelsList();
                JSONArray summaryList = paasFormEntityExt.getSummaryList();
                formEntityAddDTO.setBusinessType(jxcMenuEnum.getCode());
                formEntityAddDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                formEntityAddDTO.setLabels(JsonHelperUtil.parseArray(labelsList.toJSONString(), SummaryDataPoJo.class));
                formEntityAddDTO.setCustomTitle(JsonHelperUtil.parseArray(customTitle, FormTitlePoJo.class));
                formEntityAddDTO.setSummaryEntity(JsonHelperUtil.parseArray(summaryList.toJSONString(), SummaryDataPoJo.class));
                formEntityAddDTO.setMenuId(item.getId());
                formEntityAddDTO.setId(null);
                formList.add(formEntityAddDTO);
            }
        } catch (XbbException e) {
            throw e;
        }
        return formList;
    }


    private PaasMenuEntity getMenu(PaasAppEntity item, JXCRemouldMenuEnum menuEnum, String userId, Long now, Map<Long, Integer> appIdAndCount, Map<String, PaasMenuEntity> groupMenuMap) {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        paasMenuEntity.setCorpid(item.getCorpid());
        paasMenuEntity.setAppId(item.getId());
        paasMenuEntity.setCreatorId(userId);
        paasMenuEntity.setAlias(menuEnum.getAlias());
        paasMenuEntity.setColor(menuEnum.getAccessLinkEnum().getColor());
        paasMenuEntity.setIcon(menuEnum.getAccessLinkEnum().getIcon());
        paasMenuEntity.setParentId(0L);
        if (Objects.nonNull(groupMenuMap.get(menuEnum.getParent()))) {
            // 父节点
            paasMenuEntity.setParentId(groupMenuMap.get(menuEnum.getParent()).getId());
        }
        paasMenuEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        paasMenuEntity.setUrl(menuEnum.getAccessLinkEnum().getUrl());
        paasMenuEntity.setMobileUrl(menuEnum.getAccessLinkEnum().getMobileUrl());
        paasMenuEntity.setType(menuEnum.getType());
        paasMenuEntity.setEnable(BasicConstant.ONE);
        paasMenuEntity.setName(menuEnum.getName());
        paasMenuEntity.setCreatorId(userId);
        paasMenuEntity.setAddTime(now);
        paasMenuEntity.setUpdateTime(now);

        Integer count = appIdAndCount.get(item.getId());
        if (count != null) {
            count += 1;
            paasMenuEntity.setSort(count);
        } else {
            paasMenuEntity.setSort(100);
        }
        return paasMenuEntity;
    }

    private PaasMenuEntity getMenu(PaasAppEntity item, JXCRemouldMenuEnum menuEnum, String userId, Long now, Map<Long, Integer> instockSortMap,
                                   Map<Long, Integer> outstockSortMap,Map<String, PaasMenuEntity> groupMenuMap) {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        paasMenuEntity.setCorpid(item.getCorpid());
        paasMenuEntity.setAppId(item.getId());
        paasMenuEntity.setCreatorId(userId);
        paasMenuEntity.setAlias(menuEnum.getAlias());
        paasMenuEntity.setColor(menuEnum.getAccessLinkEnum().getColor());
        paasMenuEntity.setIcon(menuEnum.getAccessLinkEnum().getIcon());
        paasMenuEntity.setParentId(0L);
        if (Objects.nonNull(groupMenuMap.get(menuEnum.getParent()))) {
            // 父节点
            paasMenuEntity.setParentId(groupMenuMap.get(menuEnum.getParent()).getId());
        }
        paasMenuEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        paasMenuEntity.setUrl(menuEnum.getAccessLinkEnum().getUrl());
        paasMenuEntity.setMobileUrl(menuEnum.getAccessLinkEnum().getMobileUrl());
        paasMenuEntity.setType(menuEnum.getType());
        paasMenuEntity.setEnable(BasicConstant.ONE);
        paasMenuEntity.setName(menuEnum.getName());
        paasMenuEntity.setCreatorId(userId);
        paasMenuEntity.setAddTime(now);
        paasMenuEntity.setUpdateTime(now);

        switch (menuEnum) {
            case PURCHASE_INSTOCK:
                paasMenuEntity.setSort(instockSortMap.getOrDefault(item.getId(), 3) - 2);
                break;
            case REFUND_INSTOCK:
                paasMenuEntity.setSort(instockSortMap.getOrDefault(item.getId(), 3) - 1);
                break;
            case PRODUCTION_INSTOCK:
                paasMenuEntity.setSort(instockSortMap.getOrDefault(item.getId(), 3) + 1);
                break;
            case RETURNED_MATERIEL_INSTOCK:
                paasMenuEntity.setSort(instockSortMap.getOrDefault(item.getId(), 3) + 2);
                break;
            case CONTRACT_OUTSTOCK:
                paasMenuEntity.setSort(outstockSortMap.getOrDefault(item.getId(), 3) - 2);
                break;
            case RETURNED_PURCHASE_OUTSTOCK:
                paasMenuEntity.setSort(outstockSortMap.getOrDefault(item.getId(), 3) - 1);
                break;
            case PRODUCTION_MATERIEL_OUTSTOCK:
                paasMenuEntity.setSort(outstockSortMap.getOrDefault(item.getId(), 3) + 1);
                break;
            case WORK_ORDER_OUTSTOCK:
                paasMenuEntity.setSort(outstockSortMap.getOrDefault(item.getId(), 3) + 2);
                break;
            default:
                break;
        }
        return paasMenuEntity;
    }

    @RequestMapping(value = "/addDefaultJXCPrintTemplate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public String addDefaultJXCPrintTemplate(@RequestBody @Valid PrintTemplateDTO printTemplateDTO,BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(printTemplateDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList;
        if (CollectionsUtil.isNotEmpty(printTemplateDTO.getCorpidList())) {
            corpidList = printTemplateDTO.getCorpidList();
        } else {
            corpidList = companyModel.getCorpidList();
        }
        // 提取全局默认模板
        List<Integer> businessTypeList = Arrays.asList(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(),XbbRefTypeEnum.REFUND_INSTOCK.getCode(),XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode(),XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode(),
                XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(),XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(),XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode(),XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode());

        Map<String, Object> defaultTemplateParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        defaultTemplateParam.put("corpid", "0");
        defaultTemplateParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        defaultTemplateParam.put("businessTypeIn", businessTypeList);
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateModel.list(defaultTemplateParam);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return "数据库中没有存在默认模板配置";
        }
        Map<Integer, PaasPrintTemplateEntity> defaultTemplateMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasPrintTemplateEntity templateEntity : defaultList) {
            defaultTemplateMap.put(templateEntity.getBusinessType(), templateEntity);
        }

        int total = corpidList.size();
        int page = 0;
        int pageSize = 10;
        while (page * pageSize < total){
            List<String> subCorpidList;
            if ((page + 1) * pageSize > total){
                subCorpidList = corpidList.subList(page * pageSize,total);
            }else {
                subCorpidList = corpidList.subList(page * pageSize,(page + 1) * pageSize);
            }
            Map<String, Object> formParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            formParam.put("corpidIn",subCorpidList);
            formParam.put("businessTypeIn", businessTypeList);
            formParam.put("columns","id,app_id,menu_id,business_type,corpid");
            List<PaasFormEntityExt> formEntityExts = paasFormModel.findEntitys(formParam);
            initDefaultJXCPrintTemplates(formEntityExts, defaultTemplateMap);
            page++;
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("addDefaultJXCPrintTemplate over");
        return "success";
    }

    private void initDefaultJXCPrintTemplates(List<PaasFormEntityExt> formList, Map<Integer, PaasPrintTemplateEntity> defaultTemplateMap) throws Exception {
        long now = DateTimeUtil.getInt();
        List<PaasPrintTemplateEntity> insertList = new ArrayList<>();
        for (PaasFormEntity paasFormEntity : formList) {
            Integer businessType = paasFormEntity.getBusinessType();
            PaasPrintTemplateEntity defaultEntity = defaultTemplateMap.get(businessType);
            if (defaultEntity == null) {
                continue;
            }
            // 插入新默认模板
            PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity();
            paasPrintTemplateEntity.setName("默认模板");
            paasPrintTemplateEntity.setCorpid(paasFormEntity.getCorpid());
            paasPrintTemplateEntity.setAppId(paasFormEntity.getAppId());
            paasPrintTemplateEntity.setMenuId(paasFormEntity.getMenuId());
            paasPrintTemplateEntity.setFormId(paasFormEntity.getId());
            paasPrintTemplateEntity.setCreatorId("0");
            paasPrintTemplateEntity.setAddTime(now);
            paasPrintTemplateEntity.setUpdateTime(now);
            paasPrintTemplateEntity.setBusinessType(businessType);
            paasPrintTemplateEntity.setHtml(defaultEntity.getHtml());
            paasPrintTemplateEntity.setConfigInfo(defaultEntity.getConfigInfo());
            insertList.add(paasPrintTemplateEntity);
        }
        if (insertList.size() > 0) {
            paasPrintTemplateModel.insertBatch(insertList);
        }
        LOG.warn(insertList.size() + "条打印模板插入成功");
    }

    /**
     * 获取公司数量
     *
     * @return int
     * @author 徐俊杰
     * @date 2019/12/2 14:07
     * @since v1.0
     */
    private int companyCount() {
        Map<String, Object> param = new HashMap<>(16);
        param.put("del", 0);
        param.put("status", 1);
        return companyModel.getEntitysCount(param);
    }

    /**
     * 获取公司ids
     *
     * @param i 起始的数量
     * @return java.util.List<java.lang.String>
     * @author 徐俊杰
     * @date 2019/12/2 14:27
     * @since v1.0
     */
    private List<String> corpids(int i) {
        int pageSize = 100;
        Map<String, Object> param = new HashMap<>(16);
        param.put("del", 0);
        param.put("status", 1);
        param.put("start",i);
        param.put("pageNum",pageSize);
        param.put("columns","corpid");
        List<CompanyEntity> companyEntityList = companyModel.findEntitys(param);
        if (Objects.isNull(companyEntityList) || companyEntityList.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> corpids = new ArrayList<>(pageSize);
        companyEntityList.forEach(item -> corpids.add(item.getCorpid()));
        return corpids;
    }

    /**
     * 获取应用开启的列表
     *
     * @param corpids 公司ids
     * @param alias 别名
     * @return java.util.List<com.xbongbong.paas.domain.entity.PaasAppEntity>
     * @author 徐俊杰
     * @date 2019/12/2 14:32
     * @since v1.0
     */
    private List<PaasAppEntity> appEnableList(List<String> corpids, String alias) {
        Map<String,Object> appParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        appParam.put("del", 0);
        appParam.put("corpidIn", corpids);
        appParam.put("alias", alias);
        appParam.put("enable",BasicConstant.ONE);
        return paasAppModel.findEntitys(appParam);
    }

    /**
     * 根据业务批量插入默认打印模板
     *
     * @param businessTypeIn 业务类型
     * @param corpids 公司id集合
     * @param defaultTemplateMap 业务类型-默认模板-map
     * @author 徐俊杰
     * @date 2019/12/31 9:09
     * @since v1.0
     */
    private void insertDefaultTemplate(List<Integer> businessTypeIn, List<String> corpids, Map<Integer, PaasPrintTemplateEntity> defaultTemplateMap) {
        //获取表单
        List<PaasFormEntityExt> formList = formList(businessTypeIn, corpids);
        if (formList.isEmpty()) {
            LOG.warn("----------------------formList null" );
            return;
        }
        LOG.warn("--cid.size()：" + corpids.size() + "----------------------formList.size():" + formList.size());
        //包装要插入的模板
        List<PaasPrintTemplateEntity> insertList = insertList(formList, defaultTemplateMap);
        try {
            if (CollectionsUtil.isNotEmpty(insertList)) {
                LOG.warn("----------------------插入size：" + (insertList.size()));
                paasPrintTemplateModel.insertBatch(insertList);
            }
        } catch (Exception e) {
            LOG.error("初始化打印模板失败.insertDefaultTemplate：", e);
        }
    }
    private List<PaasFormEntityExt> formList(List<Integer> businessTypeIn, List<String> corpids) {
        Map<String, Object> formParam = new HashMap<>();
        formParam.put("saasMark", SaasMarkEnum.SAAS.getCode());
        formParam.put("businessTypeList", businessTypeIn);
        formParam.put("corpidIn", corpids);
        formParam.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        return paasFormModel.findEntitys(formParam);
    }

    /**
     * 业务类型-默认模板-map
     *
     * @param businessTypeIn
     * @return java.util.Map<java.lang.Integer,com.xbongbong.paas.domain.entity.PaasPrintTemplateEntity>
     * @author 徐俊杰
     * @date 2019/12/2 16:48
     * @since v1.0
     */
    private Map<Integer,PaasPrintTemplateEntity> defaultTemplateMap(List<Integer> businessTypeIn) {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del",0);
        param.put("businessTypeIn", businessTypeIn);
        param.put("corpid","0");
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateModel.list(param);
        Map<Integer,PaasPrintTemplateEntity> defaultTemplateMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return defaultTemplateMap;
        }
        for (PaasPrintTemplateEntity templateEntity : defaultList) {
            defaultTemplateMap.put(templateEntity.getBusinessType(),templateEntity);
        }
        return defaultTemplateMap;
    }

    /**
     * 打印模板列表
     *
     * @param formList 模板列表
     * @param defaultTemplateMap 业务类型-默认模板-map
     * @return java.util.List<com.xbongbong.paas.domain.entity.PaasPrintTemplateEntity>
     * @author 徐俊杰
     * @date 2019/12/2 16:52
     * @since v1.0
     */
    private List<PaasPrintTemplateEntity> insertList(List<PaasFormEntityExt> formList, Map<Integer,PaasPrintTemplateEntity> defaultTemplateMap) {
        List<PaasPrintTemplateEntity> insertList = new ArrayList<>();
        long now = DateTimeUtil.getInt();
        for (PaasFormEntity paasFormEntity : formList) {
            Integer businessType = paasFormEntity.getBusinessType();
            PaasPrintTemplateEntity defaultEntity = defaultTemplateMap.get(businessType);
            if (defaultEntity == null) {
                LOG.warn("----------------------defaultEntity null:" + businessType + "  paasFormEntity.id"+ paasFormEntity.getId());
                continue;
            }
            PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity("默认模板", paasFormEntity.getCorpid(), paasFormEntity.getAppId(),
                    paasFormEntity.getMenuId(), paasFormEntity.getId(), "0", now, now, businessType, defaultEntity.getHtml(), defaultEntity.getConfigInfo());
            insertList.add(paasPrintTemplateEntity);
        }
        return insertList;
    }

    /**
     * 初始化，为公司saas模块增加默认打印模板
     * @param corpid 公司id
     * @param formList 表单列表
     * @param appAlias 应用alias
     */
    private void initDefaultPrintTemplates(String corpid,List<PaasFormEntity> formList,String appAlias, Integer distributorMark){
        List<PrintTemplateTypeEnum> printTemplateTypeList = PrintTemplateTypeEnum.getAllEnums();
        List<Integer> businessTypeList = new ArrayList<>();
        for (PrintTemplateTypeEnum printTemplateTypeEnum : printTemplateTypeList) {
            if (printTemplateTypeEnum.getApp().equals(appAlias)) {
                businessTypeList.add(printTemplateTypeEnum.getCode());
            }
        }
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("businessTypeIn",businessTypeList);
        param.put("distributorMark", distributorMark);
        Integer count = paasPrintTemplateModel.getEntitysCount(param);
        if (count != null && count > 0) {
            // 已有打印模板，结束
            return;
        }
        param.put("corpid", "0");
        param.put("del", DelEnum.NORMAL.getDel());
        List<PaasPrintTemplateEntity> defaultList = paasPrintTemplateModel.list(param);
        if (defaultList.isEmpty()) {
            // 数据库中没有存在默认模板配置
            return;
        }
        Map<Integer,PaasPrintTemplateEntity> defaultTemplateMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasPrintTemplateEntity templateEntity : defaultList) {
            defaultTemplateMap.put(templateEntity.getBusinessType(),templateEntity);
        }
        long now = DateTimeUtil.getInt();
        List<PaasPrintTemplateEntity> insertList = new ArrayList<>();
        for (PaasFormEntity paasFormEntity : formList) {
            Integer businessType = paasFormEntity.getBusinessType();
            if (!businessTypeList.contains(businessType)){
                // 无打印的业务跳过；
                continue;
            }
            PaasPrintTemplateEntity defaultEntity = defaultTemplateMap.get(businessType);
            if (defaultEntity == null) {
                continue;
            }
            PaasPrintTemplateEntity paasPrintTemplateEntity = new PaasPrintTemplateEntity();
            paasPrintTemplateEntity.setName(I18nMessageUtil.getMessage(I18nStringConstant.DEFAULT_TEMPLATE));
            paasPrintTemplateEntity.setCorpid(corpid);
            paasPrintTemplateEntity.setAppId(paasFormEntity.getAppId());
            paasPrintTemplateEntity.setMenuId(paasFormEntity.getMenuId());
            paasPrintTemplateEntity.setFormId(paasFormEntity.getId());
            paasPrintTemplateEntity.setCreatorId("0");
            paasPrintTemplateEntity.setAddTime(now);
            paasPrintTemplateEntity.setUpdateTime(now);
            paasPrintTemplateEntity.setBusinessType(businessType);
            paasPrintTemplateEntity.setHtml(defaultEntity.getHtml());
            paasPrintTemplateEntity.setConfigInfo(defaultEntity.getConfigInfo());
            paasPrintTemplateEntity.setDistributorMark(distributorMark);
            insertList.add(paasPrintTemplateEntity);
        }
        if (CollectionUtils.isEmpty(insertList)) {
            return;
        }
        try {
            paasPrintTemplateModel.insertBatch(insertList);
        }  catch (Exception e) {
            LOG.error("初始化打印模板失败：",e);
        }
    }
}
